let aliVal = {};

const getAliVal = async () => {
  try {
			uni.showLoading({
				title: "上传中..."
			});
    const res = await uni.http({
      url: "api/common/oss_sign",
			requestType: "baby"
    });
    aliVal = res.data;
  } catch (data) {
    aliVal = data;
  }
};

let uploadTask = null;
const uploadFile = async (filePath) => {
  return new Promise(async (resolve, reject) => {
    const date = Date.now();
    const { host, dir, policy, accessid, signature } = aliVal;

    try {
      uploadTask=uni.uploadFile({
        url: host, // oss 开发服务器地址
        filePath,
        name: "file",
        formData: {
          // oss 配置信息
          key: `${dir}h-baby/${date}`,
          policy,
          OSSAccessKeyId: accessid,
          signature,
        },
      });

      const networkUrl = `${host}/${dir}h-baby/${date}`;

			setTimeout(async () => {
	      const res = await uni.http({
	        url: `https://weapp.miyingbl.com/api/common/examine_image_to_tx?image=${networkUrl}`,
					requestType: "baby"
	      });
	      uni.hideLoading();
	      return res.data ? resolve(networkUrl) : reject(res.data);
      }, 500)
    } catch (err) {
      throw err;
    }
  });
};

// 停止上传视频
export const stopUpload = async() => {
  if (uploadTask !== null && typeof uploadTask === 'object') {
    // 取消上传任务
    uploadTask.abort();
    
    // 清空上传任务引用
    uploadTask = null;
  } else {
    console.error('没有正在进行的上传任务');
  }
}
export const uploadApi = async (filePaths) => {
  const urls = Array.isArray(filePaths) ? filePaths : [filePaths];
  if (!aliVal.host || Object.keys(aliVal).length === 0) {
    await getAliVal();
  }
  const uploadPromises = urls.map(uploadFile);
  try {
    const results = await Promise.all(uploadPromises);
    return Array.isArray(filePaths) ? results : results[0];
  } catch (error) {
    throw error;
  }
};
